# 项目有三个导包路径,但pycharm默认只有一个,需要手动设置
# from meiduo_mall.meiduo_mall.libs.yuntongxun.sms import CCP
from rest_framework import status

# from meiduo_mall.libs.yuntongxun.sms import CCP  # 设置source root 防止pycharm报红

from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
from celery_tasks.sms.tasks import send_sms_code
from . import constants
from random import randint
import logging
logger = logging.getLogger('django')  # 创建日志输出器


# Create your views here.

# http://api.meiduo.site:8000/sms_codes/18128860465/
class SMSCodeView(APIView):
    """发送短信验证码"""

    def get(self, request, mobile):

        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')

        # 判断⽤用户是否是在60s内发送短信
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:  # 如果此手机号在60秒内发过短信提前响应不执行后续发短信代码
            return Response({'message':'频繁发送短信'}, status=status.HTTP_400_BAD_REQUEST)

        # 生成短信验证码
        sms_code = '%06d' % randint(0, 999999)
        logger.info("短信验证吗: %s" % sms_code)

        # 利用容联云通讯发短信
        # CCP().send_template_sms(self, to, datas, temp_id):
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)

        # 触发celery异步任务
        # send_sms_code(mobile, sms_code)  # 千万不要这样写,这样和执行普通函数没区别
        send_sms_code.delay(mobile, sms_code)

        # 创建管道
        pl = redis_conn.pipeline()
        # 保存短信验证码
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 保存发送短信验证码的标记
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 执⾏行行
        pl.execute()
        # 5.响应
        return Response({'message': 'ok'})